package com.ztil.net;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;

/**
 * HTTP POST和GET处理工具类
 */
public class HttpUtils {
//	private static Logger logger = LogManager.getLogger(HttpUtils.class.getName());

	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数
	 * @return URL 所代表远程资源的响应结果
	 * @throws Exception
	 */
	public static String sendGet(String url, Map<String, String> params) throws Exception {
		/** 组装参数 **/
		String param = parseParams(params, true);
		String urlNameString = url + "?" + param;
		URL realUrl = new URL(urlNameString);
		/** 打开和URL之间的连接 **/
		HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
		connection.setRequestMethod("GET");
		/** 设置通用的请求属性 **/
		connection.setRequestProperty("accept", "*/*");
		connection.setRequestProperty("connection", "Keep-Alive");
		connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		/** 建立实际的连接 **/
		connection.setConnectTimeout(5000);
		connection.connect();
		/** 定义 BufferedReader输入流来读取URL的响应 **/
		String line;
		StringBuilder sb = new StringBuilder();
		try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"))) {
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream(), "UTF-8"))) {
				while ((line = br.readLine()) != null) {
					sb.append(line);
				}
			}
//			logger.trace(url + "?" + parseParams(params, false) + "--->>>" + sb.toString());
			throw new Exception(sb.toString());
		}
//		logger.trace(urlNameString + "--->>>" + sb.toString());
		return sb.toString();

	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数
	 * @return 所代表远程资源的响应结果
	 * @throws Exception
	 */
	public static String sendPost(String url, Map<String, String> params) throws Exception {
		/** 组装参数 **/
		URL realUrl = new URL(url);
		String param = parseParams(params, true);
		/** 打开和URL之间的连接 **/
		HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
		/** 设置通用的请求属性 **/
		connection.setRequestMethod("POST");
		connection.setRequestProperty("accept", "*/*");
		connection.setRequestProperty("connection", "Keep-Alive");
		connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		/** 发送POST请求必须设置如下两行 **/
		connection.setDoOutput(true);
		connection.setDoInput(true);
		/** 设置超时 **/
		connection.setConnectTimeout(5000);
		/** 建立实际的连接 **/
		connection.connect();
		/** 定义 BufferedReader输入流来读取URL的响应 **/
		String line;
		StringBuilder sb = new StringBuilder();
		try (PrintWriter pw = new PrintWriter(connection.getOutputStream())){
			pw.write(param);
			pw.flush();
			try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"))) {
				while ((line = br.readLine()) != null) {
					sb.append(line);
				}
			} catch (Exception e) {
				try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream(), "UTF-8"))) {
					while ((line = br.readLine()) != null) {
						sb.append(line);
					}
				}
				// logger.trace(url + "?" + parseParams(params, false) + "--->>>" + sb.toString());
				throw new Exception(sb.toString());
			}
		} 
		return sb.toString();
	}

	/**
	 * 将HashMap参数组装成字符串
	 * 
	 * @param map
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws MalformedURLException
	 */
	private static String parseParams(Map<String, String> map, boolean isFormat)
			throws MalformedURLException, UnsupportedEncodingException {
		StringBuffer sb = new StringBuffer();
		if (map != null) {
			if (isFormat) {
				for (Entry<String, String> e : map.entrySet()) {
					sb.append(e.getKey());
					sb.append("=");
					sb.append(URLEncoder.encode(e.getValue(), "UTF-8"));
					sb.append("&");
				}
				sb.substring(0, sb.length() - 1);
			} else {
				for (Entry<String, String> e : map.entrySet()) {
					sb.append(e.getKey());
					sb.append("=");
					sb.append(e.getValue());
					sb.append("&");
				}
				sb.substring(0, sb.length() - 1);
			}
		}
		return sb.toString();
	}
}
